package com.bw.zg3park2212.payler

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.EnvUtils
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.entity.PaylerAddParam
import com.bw.base.entity.PaylerEntityItem
import com.bw.base.mvvm.BaseActivity
import com.bw.zg3park2212.R
import com.bw.zg3park2212.adpter.PaylerXiangAdpter
import com.bw.zg3park2212.databinding.ActivityPaylerXiangBinding
import com.bw.zg3park2212.pay.PayResult
import com.bw.zg3park2212.pay.util.OrderInfoUtil2_0
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat


@AndroidEntryPoint
@Route(path = "/app/PaylerXiangActivity")
class PaylerXiangActivity : BaseActivity<ActivityPaylerXiangBinding,PaylerViewModel>() {
    @Autowired
    lateinit var payler:PaylerEntityItem
    lateinit var paylerXiangAdpter: PaylerXiangAdpter
    var month= SimpleDateFormat("MM").format(System.currentTimeMillis())
    var year= SimpleDateFormat("yyyy").format(System.currentTimeMillis())
    var index=0

    override fun intitView() {
        ARouter.getInstance().inject(this)
        viewmodel.getpaylerxiang(payler.id)
        paylerXiangAdpter= PaylerXiangAdpter()
        binding.rvPaydeatil.adapter=paylerXiangAdpter
        binding.rvPaydeatil.layoutManager= LinearLayoutManager(this)
        viewmodel.getpayler(2)
        paylerXiangAdpter.addChildClickViewIds(R.id.paydetail_cb)
        paylerXiangAdpter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.paydetail_cb->{
                    paylerXiangAdpter.data[position].idChecked=!paylerXiangAdpter.data[position].idChecked
                    index=position
                }
            }
            checkqian()
        }
        binding.cbAll.setOnClickListener {
          paylerXiangAdpter.data.forEach {
              it.idChecked=binding.cbAll.isChecked
          }
            paylerXiangAdpter.notifyDataSetChanged()
            checkqian()
        }
        binding.btnPay.setOnClickListener {
            //开启沙箱
            EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
            pay();

        }
    }
    //计算金额+是否全选
    private fun checkqian() {
        var sum=0f
        paylerXiangAdpter.data.forEach {
            if (it.idChecked){
                sum+=it.chargeAmount
            }
        }
        binding.paydetailCkmoney.text="¥:$sum"
        //计算是否全选
        var list= mutableListOf<Boolean>()
        paylerXiangAdpter.data.forEach {
            list.add(it.idChecked)
        }
        if (false in list){
            binding.cbAll.isChecked=false
        }else{
            binding.cbAll.isChecked=true
        }
    }

    override fun intitData() {
        viewmodel.paylerxiangSuccse.observe(this){
            binding.itempayUname.text="缴费人:"+it.payerName
            binding.itempayPhone.text="联系电话:"+it.contactNumber

        }
        viewmodel.paylerSuccse.observe(this){
            paylerXiangAdpter.data.clear()
            paylerXiangAdpter.addData(it.filter { it.paymentTime.split("-")[0]==year && it.paymentStatus=="未缴费" })
            var sum1=0
            paylerXiangAdpter.data.forEach {
                sum1+=it.chargeAmount
            }
            binding.itempayTotal.text="￥$sum1"
            paylerXiangAdpter.notifyDataSetChanged()
        }
        viewmodel.paylerupSuccse.observe(this){
            viewmodel.getpayler(2)
            ToastUtils.showLong("修改成功")
        }
    }
    override fun onResume() {
        super.onResume()
        viewmodel.getpayler(2)
    }
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    val APPID = "2021000118655415"

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    val PID = ""

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    val TARGET_ID = ""

    /**
     * pkcs8 格式的商户私钥。
     *
     *
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     *
     *
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    val RSA2_PRIVATE =
        "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCpf4lEigXwChQW6OPYC4lhgBNOI25JVMgnr0DWHHfSha3SqskPDCGs/Qk8f4WVjregCgbiD6sAX4UBi50srJULiDytlKjyKVhmEe4ZTw3xG/cJ/lfQZ2/aC46tD5eFEXDh/7shGiQEflDZBXJ4amaicBCNTcISz6fxaRWtab5DbWqMvZBX2xOr0gUzu6l1RE//tXMtyJD3yyVM6/A5zIeReqSfzrok1ZAW1GhRLsvZJPpvY+v95UE2fXUt8y3piFxvheRGQ7I5RVNW4/8TGJ7RemnNOyaT3c/aDnNUNq/wKFZ0UAm8rf2/WYeHcLATXIjk3wSl0LzehEG6l3qTabeFAgMBAAECggEAYToIKmml+Eg/t9iFgdM0TdpiuIq4Y5YfbiwoW+lejkMiL1rKFDiYRJutJafcn6qLCGFYC2qDY6ZnLDjCwvKIWGIgtE03EBnJXFtiod/oFms9LN1Zz/DVh1Tj1b/A4ZLclrbTx6wwBufSRnrKa+pUz07LH9L/xTyakG8AAUZL3m693DRUXbvC7QdzBaIWY6wvVMM/3Gv4L2KK/dd7DOTzzkn1GB+g1BNYtJW1LuZUUDkEYKaHps98U+rH0xf63AlRRdjCp1la8Wso+9y2B+Wrrg3QpTzmwVXo4f2nQgYTNhyD3XTN/scN+vSb28UyS4EnGBv89UmtaNc8bKAVaF4IDQKBgQD1j/fznQt4iPdubS2w5FcdP2cXqj0EC0S2+M4ncYeimN/Ag0kZnFz7rVFoYfX6RFLlxtRpWjN764+rHpO6mTdNdWFSbqrFj3yXtomcJzGtERPrPB6zT2Gy60UjPh0I5sC9QX+NMtVkxlAdfw5BBPbLfksUeSQcjXizLF2S/GlLJwKBgQCws+RzJ9WrRRrAFwgjYzxgIcU+wiYIca91Ew8vVAT1no+ayjwIvQOaVI/g7OczuFhRWXV1+kzcyJ9+AmGRkAqU/hCnjQ62Eh2z3PLUsfP0MrnzRcAaWAR9r9ANhd+m6bNBVsP10Q/57+oapgmNWSG2gCekTg0w4nhqiiMJhRiDcwKBgQCnquGWSUinyH2JvKpR+dcxdTUjB24Z8Me+VywL6oy+DLvaasni3szuW20WZKzbcQNZOOWX+arllfXG1V3xLuR/0wHckwuvUUW1IUHciTZ2AQ8ksywTKsR+sf3HDoYsqcI4dxxsgKUL5gyV10cYRhds4pLJK93oUQB09nn9/rK2SQKBgCmLIbqxMtsBdDiVMaSgQCGZzvXiT27My6OKx5co+cGFdd2+jj6/sYknOGx5RiIyxRDbJ3KFVmzR/i1yAd5nLxW4ZdH+p+bGe5U97Rl0fRZ8lptLWs7WwreKDjAfuWVUrIBAFfJFJKxua2u4faZtvi9aEfffIdrMY+ModvRWBl1hAoGBAN2aTPLeKIhyKNg/8IIYcST7ixgCHLnT2fxmK7qnKd4Y0QtqMyQM+xwA5A89xUU8b8Q/+Z11UkM5ysh74dFR6R7Oha9Lw8V2ovx6vQLOATEK28X7FIBsolBPwMjAn572QN9eAP+uRe5Yu2KfiX6ez8D61rEFee+3AtnRHumDJokr"
    val RSA_PRIVATE = ""

    private val SDK_PAY_FLAG = 1
    private val SDK_AUTH_FLAG = 2

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(this@PaylerXiangActivity, "支付成功", Toast.LENGTH_SHORT).show()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        var list= mutableListOf<Boolean>()
                        paylerXiangAdpter.data.forEach {
                            list.add(it.idChecked)
                        }

                        if (list.contains(true)){
                            for (i in paylerXiangAdpter.data.indices){
                                if(paylerXiangAdpter.data[i].idChecked){
                                    var paylerAddParam =PaylerAddParam()
                                    paylerAddParam.paymentStatus="已缴费"
                                    paylerXiangAdpter.data.forEach {
                                        paylerAddParam.actualAmount= it.actualAmount
                                        paylerAddParam.chargeAmount= it.chargeAmount
                                        paylerAddParam.receivableAmount= it.receivableAmount
                                        paylerAddParam.chargeType= it.chargeType
                                        paylerAddParam.payerName= it.payerName
                                        paylerAddParam.contactNumber= it.contactNumber.toLong()
                                    }
                                    viewmodel.getpaylerup(paylerXiangAdpter.data[i].id,paylerAddParam)
                                }
                            }
                        }
                        var summ=0f
                        binding.paydetailCkmoney.text="¥:$summ"
                        Toast.makeText(this@PaylerXiangActivity, "支付成功", Toast.LENGTH_SHORT).show()
                    }
                }
                else -> {}
            }
        }
    }

    /**
     * 支付宝支付业务示例
     */
    fun pay() {
        if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(
                RSA_PRIVATE
            )
        ) {
            return
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        val rsa2 = RSA2_PRIVATE.length > 0
        val params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2)
        val orderParam = OrderInfoUtil2_0.buildOrderParam(params)
        val privateKey = if (rsa2) RSA2_PRIVATE else RSA_PRIVATE
        val sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2)
        val orderInfo = "$orderParam&$sign"
        val payRunnable = Runnable {
            val alipay = PayTask(this@PaylerXiangActivity)
            val result = alipay.payV2(orderInfo, true)
            Log.i("msp", result.toString())
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }


}